package ch.bfh.ti.pixelator.preferences;

import android.content.Context;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import ch.bfh.ti.pixelator.R;

public final class TimeSliderPreference extends DialogPreference implements
		OnSeekBarChangeListener {
	private final int max;
	private final int min;
	private final int def;
	
	private int current;

	private SeekBar seekbar;
	private TextView textViewValue;

	public TimeSliderPreference(Context context, AttributeSet attributes) {
		super(context, attributes);
		min = attributes.getAttributeIntValue("http://schemas.android.com/apk/res/ch.bfh.ti.pixelator", "min", 0);
		max = attributes.getAttributeIntValue("http://schemas.android.com/apk/res/ch.bfh.ti.pixelator", "max", 0);
		def = attributes.getAttributeIntValue("http://schemas.android.com/apk/res/android", "defaultValue", 0);
	}

	@Override
	protected View onCreateDialogView() {
		current = getPersistedInt(def);
		
		LayoutInflater inflater = (LayoutInflater) getContext()
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View view = inflater.inflate(R.layout.time_slider_preference, null);

		((TextView) view.findViewById(R.id.min)).setText(Integer.toString(min));
		((TextView) view.findViewById(R.id.max)).setText(Integer.toString(max));

		seekbar = (SeekBar) view.findViewById(R.id.seekbar);
		seekbar.setMax(max - min);
		seekbar.setProgress(current - min);
		seekbar.setOnSeekBarChangeListener(this);

		textViewValue = (TextView) view.findViewById(R.id.current);
		textViewValue.setText(Integer.toString(current));

		return view;
	}

	@Override
	protected void onDialogClosed(boolean positiveResult) {
		super.onDialogClosed(positiveResult);

		if (!positiveResult) {
			return;
		}

		if (shouldPersist()) {
			persistInt(current);
		}

		notifyChanged();
	}

	@Override
	public CharSequence getSummary() {
		current = getPersistedInt(def);
		return String.format((String)super.getSummary(), current);
	}

	public void onProgressChanged(SeekBar seek, int value, boolean fromTouch) {
		current = value + min;
		textViewValue.setText(Integer.toString(current));
	}

	@Override
	public void onStartTrackingTouch(SeekBar arg0) {
	}

	@Override
	public void onStopTrackingTouch(SeekBar arg0) {
	}
}